package com.algrithom.tree.huffman;

import java.util.Map;
import java.util.Map.Entry;

/**
 * 霍夫曼解码器
 *
 * @author think
 * @version 1.0.0
 */
public class HuffmanDecoder {
    
    private final Map codeSet;
    
    public HuffmanDecoder(Map map){
        codeSet = map;
    }
    
    /**
     * 将代码段解析成消息文本
     *
     * @param code str
     * @return str
     */
    public String decode(String code){
        StringBuilder message = new StringBuilder();
        String key = "";
        char[] chars = code.toCharArray();
        for (char aChar : chars) {
            key += aChar;
            // 代码集中存在该段代码
            if (codeSet.containsValue(key)) {
                for (Object o : codeSet.entrySet()) {
                    Entry entry = (Entry)o;
                    if (entry.getValue().equals(key)) {
                        // 获取该段代码对应的键值，即消息字符
                        message.append(entry.getKey());
                    }
                }
                // 代码段变量置为0
                key = "";
            }
        }
        return message.toString();
    }
}
